import axios from 'axios'
import { getToken, removeUserInfo } from '.';
import { Toast } from 'antd-mobile';
import { createBrowserHistory } from 'umi'
const history = createBrowserHistory();
axios.defaults.baseURL = process.env.NODE_ENV === 'development' ? '/conner' : '生产环境源'
axios.defaults.timeout = 6000;
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
// 添加拦截器
axios.interceptors.request.use(function (config) {
  if (getToken()){
    if (config.method === 'get') {
      config.params = {
        ...config.params,
        token: getToken()
      }
    } else {
      config.data = {
        ...config.data,
        token: getToken()
      }
    }
  }
  return config;
}, function (error) {
  return Promise.reject(error);
});
axios.interceptors.response.use(function (res) {
  if (res.data.code === 2000) {
    // 弹出错误提示 清除登录缓存 去登录页
    removeUserInfo()
    Toast.show({
      content: '登录状态过期',
      icon: 'fail',
      afterClose: () => {
        // 去登录页
        history.replace('/login')
        history.go(0)
      }
    })
  }
  return res;
}, function (error) {
  return Promise.reject(error);
});

export default axios
